package cn.wolfcode.job;

import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.redis.JobRedisKey;
import cn.wolfcode.web.feign.SeckillProductFeignApi;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Data
public class SeckillProducCachetJob implements SimpleJob {
    @Value("${jobCron.initSeckillProduct}")
    private String cron;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SeckillProductFeignApi seckillProductFeignApi;
    @Override
    public void execute(ShardingContext shardingContext) {
        // 先获取分片的参数     10  12   14
        String time = shardingContext.getShardingParameter();
        // 远程调用秒杀服务获取指定场次秒杀的商品 List<SeckillProductVo>
        Result<List<SeckillProductVo>> result = seckillProductFeignApi.queryByTimeForJob(time);
        if (result == null || result.hasError()) {
            return;
        }
        List<SeckillProductVo> vos = result.getData();
        // key = JobRedisKey.SECKILL_PRODUCT_HASH.getRealKey(time)
        String key = JobRedisKey.SECKILL_PRODUCT_HASH.getRealKey(String.valueOf(time));
        String stockCountKey = JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(String.valueOf(time));
        // 删除旧数据
        redisTemplate.delete(key);
        // 存入新数据
        for (SeckillProductVo vo : vos) {
            redisTemplate.opsForHash().put(key,String.valueOf(vo.getId()), JSON.toJSONString(vo));
            redisTemplate.opsForHash().put(stockCountKey,String.valueOf(vo.getId()),String.valueOf(vo.getStockCount()));
        }

    }
}
